package com.ruoyi.mf178.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.ruoyi.common.utils.http.HttpUtils;
import com.ruoyi.mf178.domain.Mf178Order;
import com.ruoyi.mf178.domain.Mf178SupplyGood;
import com.ruoyi.mf178.domain.Mf178TradeResponse;
import com.ruoyi.mf178.service.IMf178CouponTradeService;
import com.ruoyi.mf178.service.IMf178OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service("starbucks_xhl")
public class CouponTradeStarbucks implements IMf178CouponTradeService {

    @Value("${starbucks_xhl.baseUrl}")
    private String baseUrl;
    @Autowired
    private IMf178OrderService mf178OrderService;

    @Override
    public Mf178TradeResponse couponTrade(Mf178SupplyGood good, Mf178Order order) {
        Map<String, String> body = new HashMap<>();
        body.put("orderNo", order.getPlatformOrderNo());
        body.put("productName", good.getGoodsName());
        body.put("skuName", good.getSpecName());
        body.put("productCode", good.getExternalCode());
        body.put("externalOrderNo", order.getExternalOrderNo());
        String url = baseUrl + "/api/mf178/order";
        String result = HttpUtils.sendPost(url, HttpUtils.mapToUrlParam(body));

        mf178OrderService.setLog(order.getExternalOrderNo(), JSONObject.toJSONString(body), result);

        JSONObject resultJson = JSONObject.parse(result);
        if (resultJson == null || resultJson.getInteger("code") == null) {
            return Mf178TradeResponse.error(999, "接口调用失败请查看日志");
        }
        if (!resultJson.getInteger("code").equals(200)) {
            return Mf178TradeResponse.error(resultJson.getInteger("code"), resultJson.getString("msg"));
        }
        JSONObject data = resultJson.getJSONObject("data");
        return Mf178TradeResponse.success(data.getString("orderNo"), null, data.getString("cardNo"), "3", data.getBigDecimal("costPrice"));
    }

    @Override
    public String cardStatus(Mf178Order order) {
        Map<String, String> body = new HashMap<>();
        body.put("externalOrderNo", order.getExternalOrderNo());
        body.put("cardNo", order.getCardNo());
        body.put("cardPwd", order.getCardPwd());
        String url = baseUrl + "/api/mf178/cardStatus";
        String result = HttpUtils.sendPost(url, HttpUtils.mapToUrlParam(body));
        return result;
    }

    @Override
    public String dropCard(Mf178Order order) {
        Map<String, String> body = new HashMap<>();
        body.put("externalOrderNo", order.getExternalOrderNo());
        body.put("cardNo", order.getCardNo());
        body.put("cardPwd", order.getCardPwd());
        String url = baseUrl + "/api/mf178/dropCard";
        String result = HttpUtils.sendPost(url, HttpUtils.mapToUrlParam(body));
        return result;
    }
}
